package url;

import java.io.*;
import java.net.MalformedURLException;
import java.net.URL;

//获取资源:源代码
//流
public class URLDemo02 {
    public static void main(String[] args) {
        try {
            URL url=new URL("http://www.baidu.com");//主页/默认资源
            //获取资源 网络流
            /*
            InputStream is=url.openStream();
            byte[] flush=new byte[1024];
            int len=0;
            while ((len=is.read(flush))!=-1){
                System.out.println(new String(flush,0,len,"utf-8"));
            }
            is.close();
             */
            //使用转换流
            //爬虫原理
            InputStreamReader isr=new InputStreamReader(url.openStream(),"UTF-8");
            BufferedReader br=new BufferedReader(isr);
            FileOutputStream fos=new FileOutputStream("baidu.html");//指出要保存的文件路径及文件名
            OutputStreamWriter osw=new OutputStreamWriter(fos,"UTF-8");
            BufferedWriter bw=new BufferedWriter(osw);
            String msg=null;
            while ((msg=br.readLine())!=null){
                System.out.println(msg);
                //bw.write(msg);
                bw.append(msg);//两种方式都行
                //bw.newLine();//换行 最好手动换行,以免不同系统换行符错误
                bw.write("\r\n");//手动换行
            }
            isr.close();
            br.close();
            bw.flush();
            bw.close();
            fos.close();
            osw.close();

        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
